package com.qf.config;


//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼            BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  



import com.qf.entity.TMenu;
import com.qf.mapper.MenuMapper;
import com.qf.security.MyFailHandler;
import com.qf.security.MySuccessHandler;
import com.qf.security.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * Created by jackiechan on 2021/11/1 14:19
 * springsecurity 的配置类,是一个适配器模式,主要做转换用的
 * @author jackiechan
 * @version 1.0
 * //TODO 给最美丽的芳姐介绍学生
 * @since 1.0
 */
@EnableWebSecurity//开启 springsecurituy
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {


    private MyFailHandler myFailHandler;


    private MySuccessHandler mySuccessHandler;


    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Autowired
    public void setMySuccessHandler(MySuccessHandler mySuccessHandler) {
        this.mySuccessHandler = mySuccessHandler;
    }

    @Autowired
    public void setMyFailHandler(MyFailHandler myFailHandler) {
        this.myFailHandler = myFailHandler;
    }

    private MyUserDetailsService myUserDetailsService;

        @Autowired
    public void setMyUserDetailsService(MyUserDetailsService myUserDetailsService) {
        this.myUserDetailsService = myUserDetailsService;
    }

    private MenuMapper menuMapper;

    @Autowired
    public void setMenuMapper(MenuMapper menuMapper) {
        this.menuMapper = menuMapper;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
        //配置了用户的查询方式以及密码的比较方式
        auth.userDetailsService(myUserDetailsService).passwordEncoder(bCryptPasswordEncoder);//设置用户查询的东西
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/","/index.html","/css/**","/js/**","*.js","*.css","/swagger-ui.html","/webjars/**");//放行地址
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();//关闭跨域的操作,将允许一些跨域请求,特别是移动端的操作
        //配置我们的请求地址和标识之间的关系
        List<TMenu> allMenus = menuMapper.findAllMenus();//查询到项目所有设置的地址和权限的映射对象,此处应该查询缓存
        allMenus.forEach(menu->{
            try {
                //设置每个地址需要的权限
                if (!ObjectUtils.isEmpty(menu.getUrl())) {
                    http.authorizeRequests().antMatchers(menu.getUrl()).hasAuthority(menu.getPerms());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        http.authorizeRequests().anyRequest().authenticated()//我们上面设置每个地址具体的配置,有可能有些地址还没有添加到 menu表中,或者忘记了,那么我们默认这些地址必须登录才可以
                .and().formLogin().loginProcessingUrl("/login")
                .successHandler(mySuccessHandler)
                .failureHandler(myFailHandler)
                .permitAll()//设置我们登录的接口地址是/login,springsecurity 会自动生成这个接口//permitAll放行
              ///  .usernameParameter("aaaaa").passwordParameter()  //我们可以自定义 spring security 接收的用户名和密码的参数名
                .and().logout().logoutUrl("/logout");//设置退出的地址是 logout
            //    .logoutSuccessUrl("/")//退出成功后重定向到什么地址
              //  .logoutSuccessHandler();

    }
}
